#include <string.h>
#include <stdlib.h>
#include "2queue_to_stack.h"
#include "../queue/array_queue.h"


int astack_init(astack_t **s, int capacity, int size)
{
    if (NULL != *s)
        return -1;

    *s = malloc(sizeof(astack_t));

    if (NULL == *s)
        return -1;

    return !((aqueue_init(&(*s)->in_queue, capacity, size) == 0)  \
        && (aqueue_init(&(*s)->out_queue, capacity, size) == 0));
}

int astack_empty(astack_t *s)
{
    return aqueue_empty(s->in_queue);
}

int astack_full(astack_t *s)
{
    return aqueue_full(s->in_queue);
}

int astack_push(astack_t *s, const void *data)
{
    if (astack_full(s))
        return -1;

    aqueue_push(s->in_queue, data);

    return 0;
}

// 检查队列是否只有一个元素
static int __aqueue_one_elem(aqueue_t *q)
{
    return (q->head + 1) % (q->capacity + 1) == q->tail;
}

int astack_pop(astack_t *s, void *elem)
{
    void *tmp = malloc(s->in_queue->size);
    aqueue_t *qtmp = NULL;

    if (astack_empty(s) || NULL == tmp)
        return -1;
   
    while (!__aqueue_one_elem(s->in_queue)) {
        aqueue_pop(s->in_queue, tmp);
        aqueue_push(s->out_queue, tmp);
    }

    aqueue_pop(s->in_queue, elem);

    // 交换入队列和出队列
    qtmp = s->in_queue;
    s->in_queue = s->out_queue;
    s->out_queue = qtmp;

    free(tmp);
    tmp = NULL;

    return 0;
}

void astack_destroy(astack_t **s)
{
    aqueue_destroy(&(*s)->in_queue);
    aqueue_destroy(&(*s)->out_queue);
    free(*s);
    *s = NULL;
}

